package com.dz.lm.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @version 1.8;
 * @author: LDY;
 * @Description;
 * @Date: Created in 2020/7/6 19:33;
 */
public class WxMini {
    private static Properties p;
    private static InputStream in;
    private static final Logger logger = LoggerFactory.getLogger(WxMini.class);

    static {
        try {
            in = WxPay.class.getClassLoader().getResourceAsStream("wx_pay_info.properties");
            p = new Properties();
            p.load(in);
        } catch (FileNotFoundException e) {
            logger.error("WxPay Not Found File :wx_pay_info.properties");
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("WxPay IOException");
            e.printStackTrace();
        }
    }

    /**
     * 获取微信用户信息
     * @param code
     * @return
     * @throws Exception
     */
    public static Map getWxInfo(String code ,String encryptedData,String iv)throws Exception{
        Map ret = new HashMap();
        ret.put("appid", p.getProperty("wxappid"));	//开发者设置中的appId
        ret.put("secret", p.getProperty("appSecret"));	//开发者设置中的appSecret
        ret.put("js_code", code);	//小程序调用wx.login返回的code
        ret.put("grant_type", "authorization_code");	//默认参数

        String info1 = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", ret);
        Map m1 = JSONObject.parseObject(info1, Map.class);
        if(m1.get("session_key") != null && m1.get("openid") != null ){
            String openid = m1.get("openid").toString();
            String sessionkey   = m1.get("session_key").toString();
            // 解密
            byte[] encrypData = Base64Utils.decodeFromString(encryptedData);
            byte[] ivData = Base64Utils.decodeFromString(iv);
            byte[] sessionKey = Base64Utils.decodeFromString(sessionkey);
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);// 设置为解密模式

            String resultString = new String(cipher.doFinal(encrypData), "UTF-8");
            JSONObject object = JSONObject.parseObject(resultString);
            ret.put("phone",object.getString("phoneNumber"));// 拿到手机号码
            ret.put("openid",openid);// 拿到手机号码
        }
        return ret;
    }








}
